package cn.com.nes.site.interceptor;

import cn.com.nes.common.util.OpRequestWrap;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class HeaderFilter implements Filter {

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String originHeader = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", originHeader);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed", "1");
        //		response.setHeader("XDomainRequestAllowed","1");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,key");

        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            response.setStatus(200);
            return;
        }

        // chain.doFilter(new OpRequestWrap(new RequestWrapper(request)), response);

        // 由于解决不掉表单数据获取问题，只能以这种方式
        String contentType = request.getContentType();
        boolean flag = StrUtil.isNotEmpty(contentType) && contentType.contains("application/x-www-form-urlencoded");
        if (flag) {
            chain.doFilter(new OpRequestWrap(request), response);
        } else {
            chain.doFilter(new OpRequestWrap(new RequestWrapper(request)), response);
        }
    }

    public void init(FilterConfig arg0) throws ServletException {

    }

}
